import { Button, Popover, Space, Table } from 'antd';
import React, { useRef, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import { useIntl } from 'umi';
import styles from './index.less';
import ProTable from '@ant-design/pro-table';
import { postApiLogsByIndexByLimitOperate as getPagedList, } from '@/services/furion-cms/logs';
import { FileSearchOutlined, SwapRightOutlined } from '@ant-design/icons';
import ReactJson from 'react-json-view';

const OperateLogs: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [loadingVisible, handelLoadingVisible] = useState<boolean>(false);

    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const intl = useIntl();

    const operateTypes = {
        Modified: {
            text: intl.formatMessage({
                id: 'pages.operateLogs.modified',
                defaultMessage: '修改'
            }),
            status: 'Warning'
        },
        Added: {
            text: intl.formatMessage({
                id: 'pages.operateLogs.added',
                defaultMessage: '新增'
            }),
            status: 'Success'
        },
        Deleted: {
            text: intl.formatMessage({
                id: 'pages.operateLogs.deleted',
                defaultMessage: '删除'
            }),
            status: 'Error'
        }
    }

    const handleJsonObject = (jsonStr: string) => {
        try {
            const jsonObj = JSON.parse(jsonStr);
            if (typeof (jsonObj) === 'object') {
                // TODO:该错误是由 @types/react 版本引起的
                return <ReactJson key="rjv" src={jsonObj}
                name={false}
                collapsed={true}
                collapseStringsAfterLength={15}
                enableClipboard={false}
                displayObjectSize={false}
                displayDataTypes={false}
                style={{
                    display: 'inline-flex'
                }} />
            }
        } catch { }
        return jsonStr;
    }

    const columns: ProColumns<API.OperateLogDto>[] = [
        {
            title: intl.formatMessage({
                id: 'pages.operateLogs.table.appName',
                defaultMessage: '应用名称'
            }),
            dataIndex: 'appName',
            width: 150,
            search: false,
        },
        {
            title: intl.formatMessage({
                id: 'pages.operateLogs.table.operate',
                defaultMessage: '操作类型'
            }),
            dataIndex: 'operate',
            width: 120,
            search: false,
            filters: true,
            // onFilter: true,
            valueEnum: operateTypes
        },
        {
            title: intl.formatMessage({
                id: 'pages.operateLogs.table.rowKey',
                defaultMessage: '操作内容'
            }),
            dataIndex: 'rowKey',
            search: false,
            valueType: 'jsonCode',
            render: (_, entity) => {
                const fields = entity.rowContent?.map(m => m.columnName).join('，');
                const operateType = operateTypes[entity.operate!];
                const popoverContent = (<Space direction="vertical">
                    {entity.rowContent?.map(m => (<div key={m.column}>{m.columnName}：{entity.operate === 'Modified' && <>{handleJsonObject(m.oldValue || '空')} <SwapRightOutlined /></>} {handleJsonObject(m.newValue || '空')}</div>))}
                </Space>);

                const detailContent = (
                    <Popover content={popoverContent} trigger="click">
                        <Button type="link" size="small" icon={<FileSearchOutlined />} />
                    </Popover>
                )

                if (entity.operate === 'Modified') {
                    const rowKey = entity.rowKey ? `${entity.rowKey} 的 ` : ''
                    return <Space size={0}>{`${operateType?.text} ${rowKey}${fields} 数据`} {detailContent} </Space>;
                }
                else if (['Added', 'Deleted']) {
                    return <Space size={0}>{`${operateType?.text} ${entity.rowKey} 数据`} {entity.operate === 'Added' && detailContent} </Space>;
                }
                else {
                    return "-"
                }
            }
        },
        {
            title: intl.formatMessage({
                id: 'pages.operateLogs.table.user',
                defaultMessage: '操作人员'
            }),
            dataIndex: 'user',
            width: 150,
            search: false,
        },
        {
            title: intl.formatMessage({
                id: 'pages.operateLogs.table.ipAddress',
                defaultMessage: '操作IP'
            }),
            dataIndex: 'ipAddress',
            width: 150,
            search: false,
        },
        {
            title: intl.formatMessage({
                id: 'pages.operateLogs.table.createdTime',
                defaultMessage: '操作时间'
            }),
            dataIndex: 'createdTime',
            width: 150,
            valueType: 'dateRange',
            render: (dom, entity) => {
                return entity.createdTime;
            }
        },
    ]

    return (<PageContainer className={styles.main}
        breadcrumbRender={false}>
        <ProTable<API.OperateLogDto>
            rowKey="id"
            actionRef={actionRef}
            loading={loadingVisible}
            search={{ filterType: "light" }}
            pagination={{
                pageSize: 10,
                showSizeChanger: true
            }}
            rowSelection={{
                selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            }}
            columns={columns}
            request={(params, sort, filter) => {
                handelLoadingVisible(true);
                // 表单搜索项会从 params 传入，传递给后端接口。
                console.log(params, sort, filter);
                // 转换固定的参数
                const { current, pageSize, createdTime } = params;
                const [starttime, endtime] = createdTime || [];
                // 删除无效参数
                delete params.current;
                delete params.pageSize;
                delete params.createdTime;
                return getPagedList({
                    index: (current || 1),
                    limit: (pageSize || 20),
                    starttime,
                    endtime,
                    ...params
                }, (filter.operate as string[]) ?? []).then(result => {
                    const { list: data, total } = result.data || {};
                    return {
                        data,
                        success: result.success,
                        total
                    }
                }).finally(() => handelLoadingVisible(false));
            }}
        />
    </PageContainer>)
}

export default OperateLogs;